package user

import (
	"MembershipRegist/db"
	"MembershipRegist/models"
	"time"
)

// 参加活动
func (c *Controller) ActivityApply() {
	activityID, err := c.GetInt("activity_id")
	if err != nil {
		c.ResponseFailed(201, "activity_id 不合法")
		return
	}

	var activity models.OrganizationActivity
	if value := db.DB.Where("id = ?", activityID).First(&activity); value.Error != nil {
		c.ResponseFailed(202, "无此活动")
		return
	}

	userActivity := models.OrganizationUserActivity{
		OrganizationActivityID: uint(activityID),
		OrganizationID:         activity.OrganizationID,
		OrganizationAdminID:    0,
		UserID:                 c.UserID,
		CreatedAt:              time.Now(),
		UpdatedAt:              time.Now(),
		Status:                 models.UserActivityToBeReviewed,
	}

	if value := db.DB.Where("organization_activity_id = ? and user_id = ?", activityID, c.UserID).
		First(&models.OrganizationUserActivity{}); value.Error == nil {
		c.ResponseFailed(203, "你已参与活动")
		return
	}

	if value := db.DB.Create(&userActivity); value.Error != nil {
		c.ResponseFailed(204, "参加活动失败")
		return
	}

	c.ResponseSuccess()
}

func (c *Controller) ActivityApplyCancel() {
	activityID, err := c.GetInt("activity_id")
	if err != nil {
		c.ResponseFailed(201, "activity_id 不合法")
		return
	}

	db.DB.Unscoped().Delete(&models.OrganizationUserActivity{}, "organization_activity_id = ? and user_id = ?", activityID, c.UserID)
	c.ResponseSuccess()
}
